package com.example.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.example.context.BaseContext;
import com.example.example.domain.ChatConverDTO;
import com.example.example.domain.ChatConver;
import com.example.example.domain.ChatMsg;
import com.example.example.domain.MessageVO;
import com.example.example.exception.ServiceException;
import com.example.example.mapper.ChatConverMapper;
import com.example.example.mapper.ChatMsgMapper;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 消息服务实现类
 * 使用PersistentChatMemoryStore作为底层存储
 */
@Service
public class MessageService implements ChatMemoryStore {

    @Autowired
    private ChatMsgMapper chatMsgMapper;

    @Autowired
    private ChatConverMapper chatConverMapper;

    /**
     * 根据chatId获取消息列表
     *
     * @param chatId
     * @return
     */
    @Override
    public List<ChatMessage> getMessages(Object chatId) {
        // 查询指定会话ID的所有消息
        LambdaQueryWrapper<ChatMsg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMsg::getChatId, Long.valueOf(chatId.toString()));

        List<ChatMsg> chatMsgs = chatMsgMapper.selectList(queryWrapper);
        List<ChatMessage> messages = new ArrayList<>();

        // 将数据库中的消息转换为ChatMessage对象
        for (ChatMsg chatMsg : chatMsgs) {
            ChatMessage message = switch (chatMsg.getRole()) {
                case "user" -> new UserMessage(chatMsg.getContent());
                case "assistant" -> new AiMessage(chatMsg.getContent());
                case "system" -> new SystemMessage(chatMsg.getContent());
                default -> null;
            };
            if (message != null) {
                messages.add(message);
            }
        }

        return messages;
    }

    /**
     * 修改消息
     * @param chatId 会话ID
     * @param messages 消息集合
     */
    @Override
    @Transactional
    public void updateMessages(Object chatId, List<ChatMessage> messages) {
        Long converId = Long.valueOf(chatId.toString());

        // 检查会话是否存在
        ChatConver ChatConver = chatConverMapper.selectById(converId);
        if (ChatConver == null) {
            throw new ServiceException("会话不存在");
        }

        // 删除原有消息
        LambdaQueryWrapper<ChatMsg> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(ChatMsg::getChatId, converId);
        chatMsgMapper.delete(deleteWrapper);

        // 保存新消息
        for (ChatMessage message : messages) {
            ChatMsg chatMsg = new ChatMsg();
            chatMsg.setChatId(converId);
            chatMsg.setCreatedAt(new Date());

            if (message instanceof UserMessage) {
                chatMsg.setRole("user");
                chatMsg.setContent(((UserMessage) message).singleText());
            } else if (message instanceof AiMessage) {
                chatMsg.setRole("assistant");
                chatMsg.setContent(((AiMessage) message).text());
            } else if (message instanceof SystemMessage) {
                chatMsg.setRole("system");
                chatMsg.setContent(((SystemMessage) message).text());
            }

            chatMsgMapper.insert(chatMsg);
        }
    }

    @Override
    @Transactional
    public void deleteMessages(Object chatId) {
        // 删除指定会话ID的所有消息
        LambdaQueryWrapper<ChatMsg> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(ChatMsg::getChatId, Long.valueOf(chatId.toString()));
        chatMsgMapper.delete(deleteWrapper);

        // 删除会话记录
        chatConverMapper.deleteById(Long.valueOf(chatId.toString()));
    }

    /**
     * 获取记忆ID
     */
    public String getMemoryId() {

        ChatConver chatConver = new ChatConver();

        chatConver.setUserId(BaseContext.getId());
        chatConver.setTitle("新建对话");
        chatConver.setCreatedAt(new Date());
        chatConver.setUpdatedAt(new Date());

        chatConverMapper.insert(chatConver);
        return String.valueOf(chatConver.getChatId());

    }

    /**
     * 更新会话信息
     *
     * @param chatConverDTO 会话信息
     */
    public void updateChatConver(ChatConverDTO chatConverDTO) {
        Long chatId = chatConverDTO.getChatId();

        ChatConver chatConver = chatConverMapper.selectById(chatId);
        if (chatConver == null) {
            throw new ServiceException("会话不存在");
        }
        chatConver.setTitle(chatConverDTO.getTitle());
        chatConver.setUpdatedAt(new Date());
        chatConverMapper.updateById(chatConver);
    }

    /**
     * 获取消息视图对象列表
     *
     * @param chatId 会话ID
     * @return 消息视图对象列表
     */
    public List<MessageVO> getMessageVOs(Object chatId) {
        List<ChatMessage> messages = getMessages(chatId);
        return convertToVO(messages);
    }

    /**
     * 将ChatMessage列表转换为MessageVO列表
     *
     * @param messages ChatMessage列表
     * @return MessageVO列表
     */
    private List<MessageVO> convertToVO(List<ChatMessage> messages) {
        return messages.stream().map(message -> {
            if (message instanceof UserMessage userMessage) {
                return new MessageVO("user", userMessage.singleText());
            } else if (message instanceof AiMessage aiMessage) {
                return new MessageVO("assistant", aiMessage.text());
            } else if (message instanceof SystemMessage systemMessage) {
                return new MessageVO("system", systemMessage.text());
            }
            return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }
}
